package com.wnxy.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnxy.dto.LoginDto;
import com.wnxy.dto.ManagerDetail;
import com.wnxy.dto.Result;
import com.wnxy.dto.StatusCode;
import com.wnxy.service.ManagerService;
import com.wnxy.util.BeanCopyUtil;
import com.wnxy.util.DateUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class QQSuccessHandler implements AuthenticationSuccessHandler {
    private ObjectMapper om=new ObjectMapper();
    private ManagerService managerService=new ManagerServiceImpl();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Result result = Result.getInstance().setFlag(true).setStatusCode(StatusCode.SUCCESS.getCode()).setMessage("登陆成功");
        System.out.println("qq登陆成功");
        ManagerDetail md = (ManagerDetail) authentication.getPrincipal();
//        LoginDto ld = BeanCopyUtil.copyProperties(md, LoginDto.class);
        LoginDto ld = BeanCopyUtil.copyProperties(md, LoginDto.class);
        ld.setManagerLogintime(DateUtil.parseDateLong(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        result.setData(ld);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf8");
        String json=om.writeValueAsString(result);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<!DOCTYPE html>").append("<html>").append("<head><meta charset=\"utf-8\"></head>")
                .append("<script>").append("window.opener.postMessage('"+json+"','*')")
                .append("</script>")
                .append("<body>").append("<h3 style='text-align:center'>登陆成功 </h3>").append("</body></html>");
        response.getWriter().write(om.writeValueAsString(stringBuffer.toString()));
        response.getWriter().flush();
    }
}
